import pyodbc
import globalvar

class ConnPool():
    
    def __init__(self,maxconnection):
        
        self.MaxConn = maxconnection
        self.ConnQueue = []
        for i in range(0,self.MaxConn):
            globalvar.databaselogging.debug("Setup the %dth  Connection"%(i) )
            conn = pyodbc.connect(globalvar.dns_str)
            self.ConnQueue.append(conn)
            
    def GetConn(self):
        
        globalvar.DatabaseConnPool_Mutex.acquire()
        globalvar.databaselogging.debug("Get Connection")        
        conn = None
        if(len(self.ConnQueue)) > 0:
            conn = self.ConnQueue.pop()        
        else:
            globalvar.databaselogging.debug("There are more than  %d  Connection"%(self.MaxConn) )
            conn = pyodbc.connect(globalvar.dns_str)
            
        globalvar.DatabaseConnPool_Mutex.release()
            
        return conn
        
    def PutConn(self,conn):
        globalvar.DatabaseConnPool_Mutex.acquire()
        globalvar.databaselogging.debug("Put Connection")        
        if(len(self.ConnQueue))  == self.MaxConn:
            conn.close()
        else:
            self.ConnQueue.append(conn)
            
        globalvar.DatabaseConnPool_Mutex.release()
                
    def __del__(self):
        for i in range(0,self.Max_Connection):
            conn = self.ConnQueue.pop()
            conn.close()
            
        